/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Danang
 */
public class TokenList {
    // HashMap<Token,ListTokenPosition>
    HashMap<String,FieldList> tokenList;
    
    public TokenList() {
        tokenList = new HashMap<String, FieldList>();
    }
    
    public void reinit() {
        tokenList = null;
        tokenList = new HashMap<String,FieldList>();
    }
    
    public int getTokenSize() {
        return tokenList.keySet().size();
    }
    
    
    // Add Token for given position
    public void addToken_position(String token, int messageType, int messageID, ArrayList<Integer> position) {
        FieldList currToken;
        if (!tokenList.containsKey(token)) {
            currToken = new FieldList(token);
            tokenList.put(token, currToken);
        } else {
            currToken = tokenList.get(token);
        }
        currToken.addPosition(messageType, messageID, position);
    }
    
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Iterator iter = tokenList.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry pairs = (Map.Entry) iter.next();
            FieldList tokenPosition = (FieldList) pairs.getValue();
            sb.append("@@").append(tokenPosition.getToken()).append("\n");
            sb.append(tokenPosition.getAllPostingList());
        }
        return sb.toString();
    }
    
    
    // sorting isi hashmap berdasarkan urut abjad
    public List<FieldList> sortToken() {
        List<FieldList> tes = new ArrayList<FieldList>(tokenList.values());
        
        Collections.sort (tes, new Comparator<FieldList>(){
            @Override
            public int compare(FieldList o1, FieldList o2) {
                int compareResult = o1.getToken().compareTo(o2.getToken());
                return compareResult==0 ? 0 : compareResult>0 ? 1 : -1;
            }
            
        });
        
        return tes;
    }
    
    
}
